package com.atguigu.day04;

import com.atguigu.bean.Event;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import redis.clients.jedis.Jedis;

public class Flink03_Sink_Customer {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.获取数据
        SingleOutputStreamOperator<Event> streamSource = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, Event>() {
                    @Override
                    public Event map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new Event(split[0], split[1], Long.parseLong(split[2]));
                    }
                });


        //TODO 3.通过自定义Sink将数据写入Redis
        streamSource.addSink(new MyRedicSink());

        env.execute();

    }

//    public static class MyRedicSink implements SinkFunction<Event>{
    public static class MyRedicSink extends RichSinkFunction<Event> {

    private Jedis jedis;

    @Override
    public void open(Configuration parameters) throws Exception {
        System.out.println("创建链接");
        //1.获取redis链接
         jedis = new Jedis("hadoop102", 6379);
    }

    @Override
        public void invoke(Event value, Context context) throws Exception {
//            System.out.println("invoke....");


            jedis.set(value.user, value.toString());

        }

    @Override
    public void close() throws Exception {
        System.out.println("关闭链接");
        jedis.close();
    }
}


}
